package com.ruoyi.fun.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.fun.domain.EcMiniprogramConfig;
import com.ruoyi.fun.service.IEcMiniprogramConfigService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 小程序配置Controller
 * 
 * @author ruoyi
 * @date 2025-08-31
 */
@RestController
@RequestMapping("/fun/programConfig")
public class EcMiniprogramConfigController extends BaseController
{
    private static final Logger logger = LoggerFactory.getLogger(EcMiniprogramConfigController.class);
    
    @Autowired
    private IEcMiniprogramConfigService ecMiniprogramConfigService;

    /**
     * 查询小程序配置列表
     */
    @PreAuthorize("@ss.hasPermi('fun:miniprogramConfig:list')")
    @GetMapping("/list")
    public TableDataInfo list(EcMiniprogramConfig ecMiniprogramConfig)
    {
        startPage();
        // 强制设置orgId为当前用户的部门ID，确保数据隔离
        Long currentDeptId = getLoginUser().getDeptId();
        // 103组织拥有不过滤的权限
        if (currentDeptId != null && currentDeptId == 103L) {
            currentDeptId = null;
        }
        if (currentDeptId != null) {
            ecMiniprogramConfig.setOrgId(currentDeptId);
        }
        List<EcMiniprogramConfig> list = ecMiniprogramConfigService.selectEcMiniprogramConfigList(ecMiniprogramConfig);
        return getDataTable(list);
    }

    /**
     * 导出小程序配置列表
     */
    @PreAuthorize("@ss.hasPermi('fun:programConfig:export')")
    @Log(title = "小程序配置", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, EcMiniprogramConfig ecMiniprogramConfig)
    {
        List<EcMiniprogramConfig> list = ecMiniprogramConfigService.selectEcMiniprogramConfigList(ecMiniprogramConfig);
        ExcelUtil<EcMiniprogramConfig> util = new ExcelUtil<EcMiniprogramConfig>(EcMiniprogramConfig.class);
        util.exportExcel(response, list, "小程序配置数据");
    }

    /**
     * 获取小程序配置详细信息
     */
    @PreAuthorize("@ss.hasPermi('fun:programConfig:query')")
    @GetMapping(value = "/{configId}")
    public AjaxResult getInfo(@PathVariable("configId") Long configId)
    {
        return success(ecMiniprogramConfigService.selectEcMiniprogramConfigByConfigId(configId));
    }

    /**
     * 新增小程序配置
     */
    @PreAuthorize("@ss.hasPermi('fun:programConfig:add')")
    @Log(title = "小程序配置", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody EcMiniprogramConfig ecMiniprogramConfig)
    {
        ecMiniprogramConfig.setOrgId(getOrgId());
        return toAjax(ecMiniprogramConfigService.insertEcMiniprogramConfig(ecMiniprogramConfig));
    }

    /**
     * 修改小程序配置
     */
    @PreAuthorize("@ss.hasPermi('fun:programConfig:edit')")
    @Log(title = "小程序配置", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody EcMiniprogramConfig ecMiniprogramConfig)
    {
        return toAjax(ecMiniprogramConfigService.updateEcMiniprogramConfig(ecMiniprogramConfig));
    }

    /**
     * 删除小程序配置
     */
    @PreAuthorize("@ss.hasPermi('fun:programConfig:remove')")
    @Log(title = "小程序配置", businessType = BusinessType.DELETE)
	@DeleteMapping("/{configIds}")
    public AjaxResult remove(@PathVariable Long[] configIds)
    {
        return toAjax(ecMiniprogramConfigService.deleteEcMiniprogramConfigByConfigIds(configIds));
    }

    /**
     * 根据组织ID和启用状态获取小程序配置（匿名访问接口，用于小程序渲染）
     */
    @Anonymous
    @GetMapping("/public/config")
    public AjaxResult getPublicConfig(@RequestParam(required = false) Long orgId, 
                                     @RequestParam(required = false) Integer openStatus)
    {
        logger.info("=== 小程序配置匿名接口调用开始 ===");
        logger.info("请求参数 - orgId: {}, openStatus: {}", orgId, openStatus);
        
        try {
            EcMiniprogramConfig queryConfig = new EcMiniprogramConfig();
            if (orgId != null) {
                queryConfig.setOrgId(orgId);
                logger.info("设置查询条件 - 组织ID: {}", orgId);
            }
            if (openStatus != null) {
                queryConfig.setOpenStatus(openStatus);
                logger.info("设置查询条件 - 启用状态: {}", openStatus);
            }
            
            List<EcMiniprogramConfig> list = ecMiniprogramConfigService.selectEcMiniprogramConfigList(queryConfig);
            logger.info("查询结果数量: {}", list != null ? list.size() : 0);
            
            if (list != null && !list.isEmpty()) {
                EcMiniprogramConfig config = list.get(0); // 取第一个配置
                logger.info("=== 小程序配置匿名接口调用结束 ===");
                return success(config); // 返回单个对象而不是数组
            } else {
                logger.warn("未找到匹配的小程序配置");
                logger.info("=== 小程序配置匿名接口调用结束 ===");
                return success(null);
            }
            
        } catch (Exception e) {
            logger.error("获取小程序配置失败: {}", e.getMessage(), e);
            return error("获取小程序配置失败: " + e.getMessage());
        }
    }
}

